#include<head.h>


int money=1000000;        // 银行卡余额
sem_t bank_teller;       // 模拟银行柜员数量
pthread_mutex_t lock;    // 定义互斥锁
int __errnum;           //  错误码


// 银行取款函数声明
void *withdrawal(void *val);

int main(int argc, char const *argv[])
{
    int customer_arr[5] = {1, 2, 3, 4, 5};                 // 线程内部使用 展示自己是几号客户
    int customer_num = sizeof(customer_arr) / sizeof(int);  // 客户数量
    // 初始化互斥锁
    pthread_mutex_init(&lock, NULL);

    // 初始化无名信号量(银行柜员数量),用于线程同步
    sem_init(&bank_teller, 0, 3);

    // 创建客户线程号
    pthread_t tid[customer_num];

    //创建线程
    for (int i = 0; i < customer_num; i++)
    {
      
        if (0 != (__errnum = pthread_create(&tid[i], NULL, withdrawal, (void *)&customer_arr[i])))
        {
            printf("pthread_create error: %d %s\n", __errnum, strerror(__errnum));
        }
       
    }

    // 主线工作
    sleep(3);

    // V操作
    // sem_post(&bank_teller);

    //回收线程
    for (int i = 0; i < customer_num; i++)
    {
        pthread_join(tid[i],NULL);
    }

    // 销毁信号
    sem_destroy(&bank_teller);

    //销毁互斥锁
    pthread_mutex_destroy(&lock);
    return 0;
}

// 银行取款函数定义
void *withdrawal(void *val)
{
 
    int customer_id = *((int *)val);
    printf("顾客%d等待柜员中......\n", customer_id);

    pthread_mutex_lock(&lock); // 加锁
    // P操作
    sem_wait(&bank_teller);

    //顾客开始取钱
    int withdrawal = rand() % 10000 + 1000;
    money = money - withdrawal; // 修改余额
    printf("顾客%d从银行卡中取款 %d￥ \n", customer_id,withdrawal);
    sleep(3); // 模拟取款时间
    printf("顾客%d取款成功! 账号剩余余额: %d￥ \n", customer_id,money);
  
    // V操作
    sem_post(&bank_teller);
    pthread_mutex_unlock(&lock); // 解锁
    return NULL;
}